<template>
  <div>

    <!--天统计-->
    <el-date-picker v-if="state === '1'" v-model="dateDays" type="daterange" range-separator="-" style="width:100% "
      start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="shortcutsDays" :clearable="true"
      :disabled-date="pickerOptionDays" @change="handlDays" />

    <!--周统计-->
    <div v-if="state === '2'" style="width: 100%">
      <el-date-picker v-model="dateWeeks" type="week" placeholder="开始周" format=" [第] ww [周]" style="width:48% "
        class="picker" :shortcuts="shortcutsWeekStart" :clearable="true" :disabled-date="pickerOptionDays"
        @change="handlWeeks" />
      <span style="padding: 0px">-</span>
      <el-date-picker v-model="dateWeeks1" type="week" format=" [第] ww [周]" style="width:48% " placeholder="结束周"
        class="picker" :shortcuts="shortcutsWeekEnd" :clearable="true" :disabled-date="pickerOptionDays"
        @change="handlWeeks1" />
    </div>

    <!--月统计-->
    <el-date-picker v-if="state === '3'" v-model="dateMonths" style="width:100% " type="monthrange"
      :shortcuts="shortcutsMonths" range-separator="-" start-placeholder="开始月份" end-placeholder="结束月份" :clearable="true"
      @change="handlMonths" :disabled-date="pickerOptionDays" />

    <!--季统计-->
    <div v-if="state === '4'">
      <mark v-show="showSeason"
        style="position:fixed;top:0;bottom:0;left:0;right:0;background:rgba(0,0,0,0);z-index:999;"
        @click.stop="showSeason = false" />
      <el-input v-model="dateQuarters" placeholder="请选择季度" style="width:100%;" @focus="showSeason = true">
        <i slot="prefix" class="el-input__icon el-icon-date" />
      </el-input>
      <el-card v-show="showSeason" class="box-card-ji"
        style="width:322px;padding: 0 3px 20px;margin-top:10px;position:fixed;z-index:9999">
        <div slot="header" class="clearfix" style="text-align:center;padding:0">
          <button type="button" aria-label="前一年"
            class="el-picker-panel__icon-btn el-date-picker__prev-btn el-icon-d-arrow-left" @click="handlPrev" />
          <span role="button" class="el-date-picker__header-label">{{ year }}年</span>
          <button type="button" aria-label="后一年"
            class="el-picker-panel__icon-btn el-date-picker__next-btn el-icon-d-arrow-right" @click="handlNext" />
        </div>
        <div v-for="(item, index) in monthData" :key="index" class="text item" style="text-align:center;">
          <el-button type="text" size="medium" style="width:40%;color: #606266;float:left;"
            :class="selectIndex === index ? 'changeColor' : ''" @click="handlClickMonth(index)">
            {{ item }}
          </el-button>
        </div>
      </el-card>
    </div>

    <!--年统计-->
    <div v-if="state === '5'">
      <mark v-show="showYear" style="position:fixed;top:0;bottom:0;left:0;right:0;background:rgba(0,0,0,0);z-index:999;"
        @click.stop="showYear = false" />
      <el-input v-model="dataYears" placeholder="请选择年度" style="width:180px;" @focus="showYear = true">
        <i slot="prefix" class="el-input__icon el-icon-date" />
      </el-input>
      <el-card v-show="showYear" class="box-card-year"
        style="width:322px;padding: 0 3px 20px;margin-top:10px;position:fixed;z-index:9999">
        <div slot="header" class="clearfix" style="text-align:center;padding:0;width: 100%">
          <button type="button" aria-label="前十年"
            class="el-picker-panel__icon-btn el-date-picker__prev-btn el-icon-d-arrow-left" @click="handlPrevTen" />
          <span role="button" class="el-date-picker__header-label">{{ yearTime }}年</span>
          <button type="button" aria-label="后十年"
            class="el-picker-panel__icon-btn el-date-picker__next-btn el-icon-d-arrow-right" @click="handlNextTen" />
        </div>
        <div v-for="(item, index) in yearArr" :key="index" class="text item year" style="text-align:center;">
          <el-button type="text" size="medium" :class="[
              selectIndex === index ? 'changeColor' : '',
              item > year ? 'disabledColor' : ''
            ]" :disabled="item > year" style="width: 100%;color: #606266;" @click="handlClickYear(index)">{{ item }}
          </el-button>
        </div>
      </el-card>
    </div>

  </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, toRefs, watch } from "vue";
import {
  getDays,
  getMonths,
  getSeasons,
  getWeeks,
  getYears,
} from "@/utils/dateTime";
import { useRoute } from "vue-router";

export default {
  name: "DateTime",
  props: {
    state: {
      type: String,
      default: "",
    },
  },
  setup(props, context) {
    const currentInstance = getCurrentInstance();
    const route = useRoute();
    var data = reactive({
      start_time: "",
      end_time: "",
      dateDays: "",
      dateWeeks: "",
      dateWeeks1: "",
      dateMonths: "",
      dateQuarters: "",
      showSeason: false,
      valueArr: ["01-03", "04-06", "07-09", "10-12"],
      monthData: ["第一季度", "第二季度", "第三季度", "第四季度"],
      season: "",
      seasonDate: [],
      dataYears: "",
      showYear: false,
      year: new Date().getFullYear(),
      yearTime: `${new Date().getFullYear() - 5} ~ ${
        new Date().getFullYear() + 4
      }`,
      yearArr: [],
      yearDate: [],
      selectIndex: -1,
      count: 0,
      changeColor: false,
      shortcutsDays: [
        {
          text: "近7天",
          value: [getDays(7).start, getDays(7).end],
        },
        {
          text: "近一个月",
          value: [getDays(30).start, getDays(30).end],
        },
        {
          text: "近三个月",
          value: [getDays(90).start, getDays(90).end],
        },
        {
          text: "近半年",
          value: [getDays(180).start, getDays(180).end],
        },
        {
          text: "近一年",
          value: [getDays(365).start, getDays(365).end],
        },
      ], // 天快捷列表
      shortcutsWeekStart: [
        {
          text: "近四周",
          value: getWeeks(4).start,
        },
        {
          text: "近八周",
          value: getWeeks(8).start,
        },
        {
          text: "近半年",
          value: getWeeks(26).start,
        },
        {
          text: "近一年",
          value: getWeeks(52).start,
        },
      ], // 周快捷开始
      shortcutsWeekEnd: [
        {
          text: "近四周",
          value: getWeeks(4).end,
        },
        {
          text: "近八周",
          value: getWeeks(8).end,
        },
        {
          text: "近半年",
          value: getWeeks(26).end,
        },
        {
          text: "近一年",
          value: getWeeks(52).end,
        },
      ], // 周快捷结束
      shortcutsMonths: [
        {
          text: "近三个月",
          value: [getMonths(3).start, getMonths(3).end],
        },
        {
          text: "近六个月",
          value: [getMonths(6).start, getMonths(6).end],
        },
        {
          text: "近一年",
          value: [getMonths(12).start, getMonths(12).end],
        },
      ], // 月快捷列表
    });

    // 天时间限制
    const pickerOptionDays = (date) => {
      return date.getTime() > Date.now();
    };

    // 天时间事件
    const handlDays = (val) => {
      data.start_time = val[0];
      data.end_time = val[1];
      handlEmit();
    };

    // 开始周时间事件
    const handlWeeks = (val) => {
      if (val) {
        data.dateWeeks = val;
        var time = new Date(val);
        var timestamp = time.getTime() - 24 * 60 * 60 * 1000;
        if (data.dateWeeks > data.dateWeeks1 && data.dateWeeks1 !== "") {
          data.dateWeeks = data.dateWeeks1;
          data.dateWeeks1 = val;
          data.start_time = data.dateWeeks;
          data.end_time = new Date(timestamp);
        } else {
          data.start_time = new Date(timestamp);
        }
      }
      handlEmit();
    };

    // 结束周时间事件
    const handlWeeks1 = (val) => {
      if (val) {
        data.dateWeeks1 = val;
        var time = new Date(val);
        var timestamp = time.getTime() + 24 * 60 * 60 * 1000;
        if (data.dateWeeks > data.dateWeeks1 && data.dateWeeks !== "") {
          data.dateWeeks1 = data.dateWeeks;
          data.dateWeeks = val;
          data.start_time = val;
          var q = new Date(data.value5);
          var t = q.getTime() + 24 * 60 * 60 * 1000 * 5;
          data.end_time = new Date(t);
        } else {
          data.end_time = new Date(timestamp);
        }
      }
      handlEmit();
    };

    // 月时间事件
    const handlMonths = (e) => {
      var date = new Date();
      var month1 = date.getMonth() + 1;
      month1 = month1 >= 10 ? month1 : `0${month1}`;
      var days = date.getDate();
      if (e === null) {
        data.start_time = "";
        data.end_time = "";
      } else {
        const bbb =
          currentInstance.proxy.dateFormat("yyyy-mm", e[0]) +
          "-" +
          "01" +
          " " +
          "00:00:00";
        data.start_time = new Date(bbb);
        const month = currentInstance.proxy
          .dateFormat("yyyy-mm-dd ", e[1])
          .split("-")[1];
        const year = currentInstance.proxy
          .dateFormat("yyyy-mm-dd ", e[1])
          .split("-")[0];
        if (
          month === "01" ||
          month === "03" ||
          month === "05" ||
          month === "07" ||
          month === "08" ||
          month === "10" ||
          month === "12"
        ) {
          if (year === date.getFullYear() && month === month1) {
            days = days >= 10 ? days : `0${days}`;
          } else {
            days = "31";
          }
        } else if (month === "02") {
          if (year === date.getFullYear() && month === month1) {
            days = days >= 10 ? days : `0${days}`;
          } else {
            days = "28";
          }
        } else {
          if (year === date.getFullYear() && month === month1) {
            days = days >= 10 ? days : `0${days}`;
          } else {
            days = "30";
          }
        }
        const aaa =
          currentInstance.proxy.dateFormat("yyyy-mm", e[1]) +
          "-" +
          days +
          " " +
          "23:59:59";
        data.end_time = new Date(aaa);
      }
      handlEmit();
    };

    // 季度 前一年
    const handlPrev = () => {
      data.year = data.year * 1 - 1;
      data.selectIndex = -1;
    };

    // 季度 后一年
    const handlNext = () => {
      data.year = data.year * 1 + 1;
      data.selectIndex = -1;
    };

    // 季度 点击事件
    const handlClickMonth = (i) => {
      data.count++;
      data.season = i + 1;
      data.changeColor = true;
      data.selectIndex = i;
      data.seasonDate.push({
        year: data.year,
        ji: data.season,
        i: i,
      });
      if (data.count === 2) {
        if (
          data.seasonDate[0].year === data.seasonDate[1].year ||
          data.seasonDate[0].year < data.seasonDate[1].year
        ) {
          if (
            data.seasonDate[0].ji === data.seasonDate[1].ji ||
            data.seasonDate[0].ji < data.seasonDate[1].ji
          ) {
            data.dateQuarters = `${data.seasonDate[0].year}年${data.seasonDate[0].ji}季度 - ${data.seasonDate[1].year}年${data.seasonDate[1].ji}季度`;
            handlTime(
              data.seasonDate[0].year +
                "-" +
                data.valueArr[data.seasonDate[0].i].split("-")[0] +
                "~" +
                data.seasonDate[1].year +
                "-" +
                data.valueArr[data.seasonDate[1].i].split("-")[1]
            );
          } else {
            data.dateQuarters = `${data.seasonDate[1].year}年${data.seasonDate[1].ji}季度 - ${data.seasonDate[0].year}年${data.seasonDate[0].ji}季度`;
            handlTime(
              data.seasonDate[1].year +
                "-" +
                data.valueArr[data.seasonDate[1].i].split("-")[0] +
                "~" +
                data.seasonDate[0].year +
                "-" +
                data.valueArr[data.seasonDate[0].i].split("-")[1]
            );
          }
        } else {
          if (
            data.seasonDate[0].ji === data.seasonDate[1].ji ||
            data.seasonDate[0].ji < data.seasonDate[1].ji
          ) {
            data.dateQuarters = `${data.seasonDate[1].year}年${data.seasonDate[1].ji}季度 - ${data.seasonDate[0].year}年${data.seasonDate[0].ji}季度`;
            handlTime(
              data.seasonDate[1].year +
                "-" +
                data.valueArr[data.seasonDate[1].i].split("-")[0] +
                "~" +
                data.seasonDate[0].year +
                "-" +
                data.valueArr[data.seasonDate[0].i].split("-")[1]
            );
          } else {
            data.dateQuarters = `${data.seasonDate[1].year}年${data.seasonDate[1].ji}季度 - ${data.seasonDate[0].year}年${data.seasonDate[0].ji}季度`;
            handlTime(
              data.seasonDate[1].year +
                "-" +
                data.valueArr[data.seasonDate[1].i].split("-")[0] +
                "~" +
                data.seasonDate[0].year +
                "-" +
                data.valueArr[data.seasonDate[0].i].split("-")[1]
            );
          }
        }
        data.seasonDate = [];
        data.showSeason = false;
        data.count = 0;
        data.selectIndex = -1;
        data.changeColor = false;
        handlEmit();
      }
    };

    const handlTime = (val) => {
      const arr = val.split("-");
      if (arr[arr.length - 1] === "06" || arr[arr.length - 1] === "09") {
        data.start_time = new Date(
          val.split("~")[0] + "-" + "01" + " " + "00:00:00"
        );
        data.end_time = new Date(
          val.split("~")[1] + "-" + "30" + " " + "23:59:59"
        );
      } else {
        data.start_time = new Date(
          val.split("~")[0] + "-" + "01" + " " + "00:00:00"
        );
        data.end_time = new Date(
          val.split("~")[1] + "-" + "31" + " " + "23:59:59"
        );
      }
    };

    // 前十年
    const handlPrevTen = () => {
      data.selectIndex = -1;
      data.yearTime = `${Number(data.yearTime.split("~")[0]) - 5} ~ ${
        Number(data.yearTime.split("~")[1]) - 4
      }`;
      data.yearArr = [];
      const times = Number(data.yearTime.split("~")[0]);
      for (let i = 0; i < 10; i++) {
        data.yearArr.push(times + i);
      }
    };

    // 后十年
    const handlNextTen = () => {
      data.selectIndex = -1;
      data.yearTime = `${Number(data.yearTime.split("~")[0]) + 5} ~ ${
        Number(data.yearTime.split("~")[0]) + 4
      }`;
      data.yearArr = [];
      const times = Number(data.yearTime.split("~")[0]);
      for (let i = 0; i < 10; i++) {
        data.yearArr.push(times + i);
      }
    };

    // 点击确定年
    const handlClickYear = (index) => {
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var days = date.getDate();
      days = days >= 10 ? days : `0${days}`;
      data.count++;
      data.changeColor = true;
      data.selectIndex = index;
      data.yearDate.push(data.yearArr[index]);
      if (data.count === 2) {
        data.showYear = false;
        if (data.yearDate[0] > data.yearDate[1]) {
          data.dataYears = `${data.yearDate[1]}年 - ${data.yearDate[0]}年`;
          if (data.yearDate[0] === year) {
            month = month >= 10 ? month : `0${month}`;
          } else {
            month = "12";
            days = "31";
          }
          data.start_time = new Date(
            data.yearDate[1] + "-" + "01" + "-" + "01" + " " + "00:00:00"
          );
          data.end_time = new Date(
            data.yearDate[0] + "-" + month + "-" + days + " " + "23:59:59"
          );
        } else {
          data.dataYears = `${data.yearDate[0]}年 - ${data.yearDate[1]}年`;
          if (data.yearDate[1] === year) {
            month = month >= 10 ? month : `0${month}`;
          } else {
            month = "12";
            days = "31";
          }
          data.start_time = new Date(
            data.yearDate[0] + "-" + "01" + "-" + "01" + " " + "00:00:00"
          );
          data.end_time = new Date(
            data.yearDate[1] + "-" + month + "-" + days + " " + "23:59:59"
          );
        }
        data.yearDate = [];
        data.count = 0;
        data.selectIndex = -1;
        data.changeColor = false;
        handlEmit();
      }
    };

    const handlHours = (val) => {
      var date = new Date(val);
      var hours = date.getHours() + 8;
      date.setHours(hours);
      const str = date.toISOString().replace(".000Z", "+08:00");
      return str;
    };

    const handlEmit = () => {
      const a =
        currentInstance.proxy.dateFormat("yyyy-mm-dd", data.start_time) +
        " " +
        "00:00:00";
      const b =
        currentInstance.proxy.dateFormat("yyyy-mm-dd", data.end_time) +
        " " +
        "23:59:59";
      const c = { start_time: handlHours(a), end_time: handlHours(b) };
      context.emit("dateTime", c);
    };

    const handlRemove = () => {
      data.start_time = "";
      data.end_time = "";
      data.dateDays = "";
      data.dateWeeks = "";
      data.dateMonths = "";
      data.dateQuarters = "";
      data.dataYears = "";
    };

    const handlDatePicker = (val) => {
      switch (val) {
        case "1":
          if (route.query.type) {
            if (route.query.type === "1") {
              data.start_time = getDays(7).start;
              data.end_time = getDays(7).end;
            }
            if (route.query.type === "2") {
              data.start_time = getDays(30).start;
              data.end_time = getDays(30).end;
            }
            if (route.query.type === "3") {
              data.start_time = getDays(90).start;
              data.end_time = getDays(90).end;
            }
            if (route.query.type === "4") {
              data.start_time = getDays(180).start;
              data.end_time = getDays(180).end;
            }
          } else {
            data.start_time = getDays(7).start;
            data.end_time = getDays(7).end;
          }
          data.dateDays = [data.start_time, data.end_time];
          break;
        case "2":
          data.start_time = getWeeks(1).start;
          data.end_time = getWeeks(1).end;
          data.dateWeeks = data.start_time;
          data.dateWeeks1 = data.end_time;
          break;
        case "3":
          if (route.query.type) {
            if (route.query.type === "2") {
              data.start_time = getMonths(1).start;
              data.end_time = getMonths(1).end;
            }
            if (route.query.type === "3") {
              data.start_time = getMonths(3).start;
              data.end_time = getMonths(3).end;
            }
            if (route.query.type === "4") {
              data.start_time = getMonths(6).start;
              data.end_time = getMonths(6).end;
            }
          } else {
            data.start_time = getMonths(1).start;
            data.end_time = getMonths(1).end;
          }
          data.dateMonths = [data.start_time, data.end_time];
          break;
        case "4":
          data.start_time = getSeasons().start;
          data.end_time = getSeasons().end;
          data.dateQuarters = getSeasons().value;
          break;
        case "5":
          data.start_time = getYears().start;
          data.end_time = getYears().end;
          data.dataYears = getYears().value;
          break;
      }
      handlEmit();
    };

    watch(
      () => props.state,
      (newV, oldV) => {
        if (newV) {
          handlDatePicker(newV);
        }
      }
    );

    onMounted(() => {
      const time = Number(data.yearTime.split("~")[0]);
      for (let i = 0; i < 10; i++) {
        data.yearArr.push(time + i);
      }
      if (route.query.type) {
        if (route.query.type === "1") {
          handlDatePicker("1");
        } else {
          handlDatePicker("3");
        }
      } else {
        handlDatePicker("1");
      }
    });

    return {
      ...toRefs(data),
      handlDays,
      handlWeeks,
      handlWeeks1,
      handlMonths,
      pickerOptionDays,
      handlPrev,
      handlNext,
      handlClickMonth,
      handlPrevTen,
      handlNextTen,
      handlClickYear,
      handlEmit,
      handlRemove,
      handlTime,
      handlDatePicker,
    };
  },
};
</script>

<style scoped  lang="scss">
@import "@/style/basics.scss";
.changeColor {
  background-color: $main-color;
  border-radius: 18px;
}

.changeColor :deep(span) {
  color: #fff;
}

.disabledColor {
  background-color: #f5f7fa !important;
  border-radius: 18px;
}

.disabledColor :deep(span) {
  color: #c0c4cc;
}

.box-card-ji :deep(.el-card__header) {
  padding: 10px 20px;
}

.box-card-year {
  padding: 0;
}

.box-card-year :deep(.el-card__body) {
  display: flex;
  flex-wrap: wrap;
  box-sizing: border-box;
}

.box-card-year :deep(.el-card__header) {
  padding: 10px 20px;
}

.box-card-year {
  padding: 0;
}

.year {
  width: calc(25% - 10px);
  box-sizing: border-box;
  margin-right: 10px;
  margin-bottom: 10px;
}

.picker :deep(.el-input__inner) {
  padding-right: 0 !important;
}
</style>

